package com.zl.cms.controller;

import com.zl.cms.auth.AuthClass;
import com.zl.cms.auth.AuthMethod;
import com.zl.cms.dto.UserDto;
import com.zl.cms.model.ChannelTree;
import com.zl.cms.model.Role;
import com.zl.cms.model.RoleType;
import com.zl.cms.model.User;
import com.zl.cms.service.IChannelService;
import com.zl.cms.service.IGroupService;
import com.zl.cms.service.IRoleService;
import com.zl.cms.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * User: zl email:c3tc3tc3t@126.com Date: 14-1-22 Time: 上午9:56
 */
@Controller
@RequestMapping("/admin/user")
@AuthClass("login")
public class UserController {

  private IUserService userService;
  private IRoleService roleService;
  private IGroupService groupService;
  private IChannelService channelService;

  public IChannelService getChannelService() {
    return channelService;
  }

  @Inject
  public void setChannelService(IChannelService channelService) {
    this.channelService = channelService;
  }

  public IRoleService getRoleService() {
    return roleService;
  }

  @Inject
  public void setRoleService(IRoleService roleService) {
    this.roleService = roleService;
  }

  public IGroupService getGroupService() {
    return groupService;
  }

  @Inject
  public void setGroupService(IGroupService groupService) {
    this.groupService = groupService;
  }

  public IUserService getUserService() {
    return userService;
  }

  @Inject
  public void setUserService(IUserService userService) {
    this.userService = userService;
  }


  @RequestMapping("/users")
  public String list(Model model) {
    model.addAttribute("datas", userService.findUser());
    return "user/list";
  }


  private void initAddUser(Model model) {
    model.addAttribute("roles", roleService.listRole());
    model.addAttribute("groups", groupService.listGroup());
  }

  @RequestMapping(value = "/add", method = RequestMethod.GET)
  public String add(Model model) {
    // model.addAttribute("userDto",new UserDto(new User()));
    model.addAttribute("userDto", new UserDto());
    initAddUser(model);
    return "user/add";
  }

  @RequestMapping(value = "/add", method = RequestMethod.POST)
  public String add(@Valid UserDto userDto, BindingResult br, Model model) {
    if (br.hasErrors()) {
      initAddUser(model);
      return "user/add";
    }
    userService.add(userDto.getUser(), userDto.getRoleids(), userDto.getGroupids());
    return "redirect:/admin/user/users";
  }

  @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
  public String delete(@PathVariable int id) {
    userService.delete(id);
    return "redirect:/admin/user/users";
  }


  @RequestMapping(value = "/updateStatus/{id}", method = RequestMethod.GET)
  public String updateStatus(@PathVariable int id) {
    userService.updateStatus(id);
    return "redirect:/admin/user/users";
  }




	@AuthMethod
	@RequestMapping(value = "/updatepwd", method = RequestMethod.GET)
	public String updatepwd(HttpSession session, Model model) {
		User u = (User)session.getAttribute("loginUser");
		model.addAttribute(u);
		return "user/updatepwd";
	}

	@AuthMethod
	@RequestMapping(value = "/updatepwd", method = RequestMethod.POST)
	public String updatepwd(int id,String oldPwd,String password) {
		userService.updatePwd(id,oldPwd,password);
		return "redirect:/admin/user/showself";
	}

	@AuthMethod
	@RequestMapping(value = "/updateself", method = RequestMethod.GET)
	public String updateself(HttpSession session, Model model) {
		User u = (User)session.getAttribute("loginUser");
		model.addAttribute(new UserDto(u));
		return "user/updateself";
	}

	@AuthMethod
	@RequestMapping(value = "/updateself", method = RequestMethod.POST)
	public String updateself(@Valid UserDto userDto, BindingResult br, Model model,HttpSession session) {
		// 页面添加，<sf:hidden path="password"/>
		// 防止DTO验证密码为空，因为不修改密码，所以密码提交为空。所以添加这个标签，使密码不为空
		if (br.hasErrors()) {

			return "user/updateself";
		}
		User ou = userService.load(userDto.getId());
		ou.setNickname(userDto.getNickname());
		ou.setPhone(userDto.getPhone());
		ou.setEmail(userDto.getEmail());
		session.setAttribute("loginUser",ou);
		userService.update(ou);
		return "redirect:/admin/user/showself";
	}


  @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
  public String update(@PathVariable int id, Model model) {
    User u = userService.load(id);
    initAddUser(model);
    model.addAttribute("userDto",
        new UserDto(u, userService.listUserRoleids(id), userService.listUserGroupids(id)));
    return "user/update";
  }

  @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
  public String update(@PathVariable int id, @Valid UserDto userDto, BindingResult br, Model model) {
    // 页面添加，<sf:hidden path="password"/>
    // 防止DTO验证密码为空，因为不修改密码，所以密码提交为空。所以添加这个标签，使密码不为空
    if (br.hasErrors()) {
      initAddUser(model);
      return "/user/update";
    }
    User ou = userService.load(id);
    ou.setNickname(userDto.getNickname());
    ou.setPhone(userDto.getPhone());
    ou.setEmail(userDto.getEmail());
    ou.setStatus(userDto.getStatus());
    userService.update(ou, userDto.getRoleids(), userDto.getGroupids());
    return "redirect:/admin/user/users";
  }

  @RequestMapping(value = "/{id}", method = RequestMethod.GET)
  public String show(@PathVariable int id, Model model) {
    model.addAttribute(userService.load(id));
    model.addAttribute("roles", userService.listUserRoles(id));
    model.addAttribute("groups", userService.listUserGroups(id));
    return "user/show";
  }
	@RequestMapping(value="/showself")
	@AuthMethod
	public String show (Model model,HttpSession session) {
		User u  = (User)session.getAttribute("loginUser");
		model.addAttribute(u);
		model.addAttribute("groups",userService.listUserGroups(u.getId()));
		model.addAttribute("roles",userService.listUserRoles(u.getId()));
		return "user/show";

	}

  @RequestMapping("/listChannels/{uid}")
  public String listChannels(@PathVariable int uid, Model model) {
    model.addAttribute("user", userService.load(uid));
    List<Role> rs = userService.listUserRoles(uid);
    for (Role r : rs) {
      if (r.getRoleType() == RoleType.ROLE_ADMIN) {
        model.addAttribute("isAdmin", 1);
      }
    }
    return "user/listChannel";
  }

  @RequestMapping("/userTree/{uid}")
	public @ResponseBody
	List<ChannelTree> groupTree(@PathVariable Integer uid,@RequestParam(value="isAdmin",required = false) Integer isAdmin) {
		if(null != isAdmin&&isAdmin==1) {
			return channelService.generateTree();
		}
		
		return new ArrayList<>(groupService.generateUserChannelTree(uid));
	}
}
